<?php
class ZduMobileAction extends BaseAction
{
    private $wechatId;
    private $resId;
    private $mRestaurant;
    private $mOrder;
    private $mOrderGoods;
    private $mData;
    private $mGoods;
    private $mGoodsCategory;
    private $mManager;
    private $mMessage;
    private $mRestaurantInfo;
    private $mWindow;
    private $mWeekRelation;
    private $mRestaurantData;
    private $module_name;
    private $mCart;
    private $restaurantId;
    private $tablenoId;

    public function _initialize()
    {
        if (!session('userId')) {
            parent::_initialize();
        }

        if (strtolower(ACTION_NAME) !='orderdetail') {
            if (!session('userId')) {
                parent::_initialize();
            }
        }
        $this->mOrder = D('Base/RestaurantstyyOrder');
        $this->mRestaurant = D('Base/Restaurantstyy');
        $this->mOrderGoods = D('Base/RestaurantstyyOrderGoods');
        $this->mData = D('Base/RestaurantstyyData');
        $this->mGoods = D('Base/RestaurantstyyGoods');
        $this->mGoodsCategory = D('Base/RestaurantstyyGoodsCategory');
        $this->mManager = D('Base/RestaurantstyyManager');
        $this->mMessage = D('Base/RestaurantstyyMessage');
        $this->mRestaurantInfo = D('Base/RestaurantstyyInfo');
        $this->mWindow = D('Base/RestaurantstyyWindow');
        $this->mWeekRelation = D('Base/RestaurantstyyWeekRelation');
        $this->mRestaurantData = D('Base/RestaurantstyyData');
        $this->mCart = D('Base/RestaurantstyyCart');
        $action = array('notify', 'campusnotify','redisorder');
        $this->accountId = 60;
        if (!in_array(strtolower(ACTION_NAME), $action)) {

            $resId = $this->_get('res_id');
            if (!$resId) {
               // $this->error('参数错误');
            }
            $this->assign('res_id', $resId);
            $this->resId = $resId;
            // 查询模块信息
            $restaurant = $this->mRestaurant->getByPk($this->resId);

            if (!$restaurant) {
                //$this->error('该模块暂未开通');
            }

            $restaurantInfo = M('RestaurantstyyInfo')->where(array('res_id' => $this->resId, 'cut_off' => 0))->find();

            $this->restaurantId = $restaurantInfo['restaurant_id'];
            // 查询对应的模板
            if ($restaurant['module_name']) {
                $this->module_name = $restaurant['module_name'];
            } else {
                $this->module_name = 'Restaurantstyy';
            }

            session('accountId', $restaurant['account_id']);
            $this->accountId = $restaurant['account_id'];


            $this->userId = session('userId');
            $this->accountId = session('accountId');
            $this->wechatId = session('wechatId');

            $this->accountId= 5;
            if($this->_get("tableno_id")){
                $tableno_id = $this->_get("tableno_id");
                session('tableno_id',$tableno_id);
            }
            if(session('tableno_id')){
                if(session('tableno_id')<50){
                    $this->assign('title', '麦思威');
                }else{
                    $this->assign('title', '二食堂');
                }
            }

            $this->assign('res_id', $resId);
            $this->assign('account_id', $this->accountId);
            $this->assign('restaurantId', $this->restaurantId);
        }

    }


    /**
     *测试专用
     */
    public function redisOrder(){
//        $id= '668';
//        $order = $this->mOrder->getByPk($id);
//        $orderSn = $this->getOrderSn('styyApi');
//        $re = $this->_campusCardPay($order['card_number'],$order['order_amount'],$orderSn['data']);
//        echo "<pre>";
//        var_dump($re);
//        var_dump($id);

        //获取订单信息
//        $data = $this->mOrder->field('order_id')->where(array('order_num'=>array('like','%90%'),'pay_time'=>array('gt',1519574400)))->select();
//        echo "<pre>";
////        var_dump($data);exit;
//        foreach($data as $k=>$v){
//            if($v['order_id']!=668){
//                $order = $this->mOrder->getByPk($v['order_id']);
//                $orderSn = $this->getOrderSn('styyApi');
//                $re = $this->_campusCardPay($order['card_number'],$order['order_amount'],$orderSn['data']);
//                echo "<pre>";
//                var_dump($re);
//                var_dump($v['order_id']);
//                var_dump('**************');
//            }
//        }
    }



    /**
     *首页
     */
    public function index()
    {

        //根据wechat_id查询餐厅列表信息
        $condition = array('res_id' => $this->resId, 'cut_off' => 0);
        $limit = '';
        $res = $this->mRestaurantInfo->getList($condition, $limit);

        $nowTime = time();
        foreach ($res as $key => $v) {
            $time1 = strtotime(date('Y-m-d') . ' ' . $v['time1'] . ':00');
            $time2 = strtotime(date('Y-m-d') . ' ' . $v['time2'] . ':00');
            $time3 = strtotime(date('Y-m-d') . ' ' . $v['time3'] . ':00');
            $time4 = strtotime(date('Y-m-d') . ' ' . $v['time4'] . ':00');


            if (($time1 <= $nowTime && $nowTime <= $time2) || ($time3 <= $nowTime && $nowTime <= $time4)) {
                $res[$key]['stop'] = 0;
            } else {
                $res[$key]['stop'] = 1;
            }
            if ($v['user_num'] > 0) {
                $res[$key]['star'] = floor($v['score'] / $v['user_num']); //舍去法取整
                $res[$key]['grey_star'] = 5 - (floor($v['score'] / $v['user_num']));
            } else {
                $res[$key]['star'] = 0;
                $res[$key]['grey_star'] = 5;
            }

            if ($v['user_num2'] > 0) {
                $res[$key]['send_star'] = floor($v['score_send'] / $v['user_num2']); //舍去法取整
                $res[$key]['send_grey_star'] = 5 - (floor($v['score_send'] / $v['user_num2']));
            } else {
                $res[$key]['send_star'] = 0;
                $res[$key]['send_grey_star'] = 5;
            }

            if ($v['user_num3'] > 0) {
                $res[$key]['zl_star'] = floor($v['score_zl'] / $v['user_num3']); //舍去法取整
                $res[$key]['zl_grey_star'] = 5 - (floor($v['score_zl'] / $v['user_num3']));
            } else {
                $res[$key]['zl_star'] = 0;
                $res[$key]['zl_grey_star'] = 5;
            }
        }

        $data['list'] = $res;
        $name = $this->mRestaurant->getInfo(array('account_id' => $this->accountId));
        $this->assign('data', $data);
        $this->assign('name', $name);
        $this->display($this->module_name . ':index');

    }

    /**
     *菜单页
     */
    public function menu()
    {
        session('tableno_id',null);
        $url = "/restaurantstyy/ZduMobile/myorder/res_id/" . $this->resId;
        $tablenoId = $this->_get("tableno_id");
        session('tableno_id',$tablenoId);

        if ($this->accountId == 60 && !$tablenoId) {
            $this->error("请扫描餐桌二维码进入", 3, $url, 1);
        }

        if ($tablenoId) {
            $dataTable = M("RestaurantstyyTableno")->where(array("tableno_id" => $tablenoId, "cut_off" => 0))->find();

            if (!$dataTable) {
                $this->error("桌号不存在", 3, $url, 1);
            }
            if ($dataTable['status'] != 1) {
                $this->error("桌号未启用", 3, $url, 1);
            }
            session("tableno_id", $tablenoId);
        }

        $windowId = $this->_get('window_id');
//        , 'window_id' => $windowId
        $list = array();
        $con = array('restaurant_id' => $this->restaurantId,'cut_off' => 0);
        if(session('tableno_id')>50){
            $con['window_id'] = array('in','59');
        }else{
            $con['window_id'] = array('in','49,56');
        }
        if ($this->restaurantId) {
            //根据餐厅id查询所有商品种类
            $info = $this->mGoodsCategory->getList($con, '', 'sort asc');
            
            $categoryId = array();
            if ($info) {
                foreach ($info as $key => $v) {
                    $list[$v['category_id']] = $info[$key];
                    $categoryId[] = $v['category_id'];
                }
            }
            $goodsInfo = $this->mWeekRelation->getList(array('res_id' => $this->resId, 'week' => date('w')));
            $goodsId = array(0);
            if ($goodsInfo) {
                foreach ($goodsInfo as $v) {
                    $goodsId[] = $v['goods_id'];
                }
            }
            $category_id = 0;
            if ($categoryId) {
                foreach ($categoryId as $v) {
                    $res = $this->mGoods->getCount(array('goods_id' => array('in', $goodsId), 'category_id' => $v, 'cut_off' => 0, 'show' => 1));
                    if ($res > 0) {
                        $category_id = $v;
                        break;
                    }
                }
            }
        }

        //获取餐厅信息
        $info = $this->mRestaurantInfo->getByPk($this->restaurantId);
        $time1 = strtotime(date('Y-m-d') . ' ' . $info['time1'] . ':00');
        $time2 = strtotime(date('Y-m-d') . ' ' . $info['time2'] . ':00');
        $time3 = strtotime(date('Y-m-d') . ' ' . $info['time3'] . ':00');
        $time4 = strtotime(date('Y-m-d') . ' ' . $info['time4'] . ':00');
        $nowTime = time();

        if (($time1 <= $nowTime && $nowTime <= $time2) || ($time3 <= $nowTime && $nowTime <= $time4)) {

        } else {
            $str = '';
            if ($info['time1'] && $info['time1'] != "00:00" && $info['time2'] && $info['time2'] != "00:00") {
                $str .= $info['time1'] . "-" . $info['time2'] . "  ";
            }
            if ($info['time3'] && $info['time3'] != "00:00" && $info['time4'] && $info['time4'] != "00:00") {
                $str .= $info['time3'] . "-" . $info['time4'] . "  ";
            }

            $url = "/restaurantstyy/ZduMobile/myorder/res_id/" . $this->resId;

            if ($str) {
                $this->error("餐厅营业时间为：" . $str, 3, $url, 0);
            } else {
                $this->error("餐厅不在营业中", 3, $url, 0);
            }
        }

        $this->assign('restaurantId', $this->restaurantId);
        $this->assign('categoryId', $category_id > 0 ? $category_id : $categoryId[0]);
        $this->assign('info', $info);
        $this->assign('data', $list);
        $this->display($this->module_name . ':menu');
    }

    /**
     *餐厅详情
     */
    public function restaurant()
    {
        $sign = $this->_get('sign');  //为1的话视为从订单页访问的
        $restaurantId = $this->_get('id');
        $res = $this->mRestaurantInfo->getByPk($restaurantId);
        if ($res) {
            $nowTime = time();
            $time1 = strtotime(date('Y-m-d') . ' ' . $res['time1'] . ':00');
            $time2 = strtotime(date('Y-m-d') . ' ' . $res['time2'] . ':00');
            $time3 = strtotime(date('Y-m-d') . ' ' . $res['time3'] . ':00');
            $time4 = strtotime(date('Y-m-d') . ' ' . $res['time4'] . ':00');
            $time5 = strtotime(date('Y-m-d') . ' ' . $res['time5'] . ':00');
            $time6 = strtotime(date('Y-m-d') . ' ' . $res['time6'] . ':00');
            if (($time1 <= $nowTime && $nowTime <= $time2) || ($time3 <= $nowTime && $nowTime <= $time4) || ($time5 <= $nowTime && $nowTime <= $time6)) {
                $res['stop'] = 0;
            } else {
                $res['stop'] = 1;
            }

            if ($res['user_num'] > 0) {
                $res['star'] = floor($res['score'] / $res['user_num']); //舍去法取整
                $res['grey_star'] = 5 - (floor($res['score'] / $res['user_num']));
            } else {
                $res['star'] = 0;
                $res['grey_star'] = 5;
            }

            if ($res['user_num2'] > 0) {
                $res['send_star'] = floor($res['score_send'] / $res['user_num2']); //舍去法取整
                $res['send_grey_star'] = 5 - (floor($res['score_send'] / $res['user_num2']));
            } else {
                $res['send_star'] = 0;
                $res['send_grey_star'] = 5;
            }

            if ($res['user_num3'] > 0) {
                $res['zl_star'] = floor($res['score_zl'] / $res['user_num3']); //舍去法取整
                $res['zl_grey_star'] = 5 - (floor($res['score_zl'] / $res['user_num3']));
            } else {
                $res['zl_star'] = 0;
                $res['zl_grey_star'] = 5;
            }
        } else {
            $res = array();
        }
        $this->assign('sign', $sign);
        $this->assign('data', $res);
        $this->display($this->module_name . ':restaurant');
    }

    /**
     *我的订单
     */
    public function myOrder()
    {
        if ($this->_post('thirdsystem')) { //校园卡支付
            $dataResonse = $_POST;

            if (!$dataResonse['sign']) {
                $this->error("参数错误");
            }
            $campus = Service('CampusCard/CampusCard');
            $resCampus = $campus->checkCampusOrder($dataResonse, 2);

            if ($resCampus['status'] == 'S') {
                $this->campusNotify($resCampus['order_id'], $this->accountId);
            }
        }
        $type = $this->_get('type') ? $this->_get('type') : 1;
        $condition = array();
        $condition['user_id'] = $this->userId;

        if ($type == 2) {  //交易成功
            $condition['status'] = 4;
        } elseif ($type == 3) {  //等待配送
            $condition['status'] = 1;
        } elseif ($type == 4) {  //等待确认
            $condition['status'] = 2;
        } elseif ($type == 5) {  //等待评价
            $condition['status'] = 3;
        } elseif ($type == 6) {  //等待付款
            $condition['status'] = 0;
        }

        //根据fans_id查询用户的所有订单
        $info = $this->mOrder->relation(true)->getList($condition, '', 'create_time desc');

        if ($info) {
            foreach ($info as $key => $v) {
                foreach ($v['RestaurantOrderGoods'] as $val) {
                    $info[$key]['money_sum'] = ($info[$key]['money_sum'] ? $info[$key]['money_sum'] : 0) + $val['goods_num'] * $val['goods_price'];
                }
                $info[$key]['RestaurantOrderGoods']['count'] = count($v['RestaurantOrderGoods']);
            }
        }

        $this->assign('type', $type);
        $this->assign('data', $info);

        $this->display($this->module_name . ':myorder');
    }

    /**
     *确认下单
     */
    public function confirmOrders()
    {
        $orderId = $this->_get('order_id');
//		 $restaurantId = $this->_get('restaurant_id');
        $stime = $this->_get('stime');

        //校园卡状态
        $campusId = M('Campuscard')->where(array("account_id" => $this->accountId, "status" => 1))->getField("campuscard_id");
        $campusCardCard = M('CampuscardCard')->where(array('user_id' => $this->userId, "campuscard_id" => $campusId))->getField('status');
        $this->assign('campuscard_bind', $campusCardCard);
        if ($campusCardCard != 1) {
            $parameter = $this->resId . '||' . $orderId;
            $parameter = urlencode($parameter);
            $bindUrl = '/base/CampusCard/bound/account_id/' . $this->accountId . '/zdu_parameter/' . $parameter;
            $this->assign('bind_url', $bindUrl);
        }

        //根据订单号查询订单信息及订单物品表信息
        $res = $this->mOrder->relation(true)->getByPk($orderId);

        if ($res) {
            //计算总价
            $money = 0;
            foreach ($res['RestaurantOrderGoods'] as $v) {
                $money = $money + ($v['goods_price'] * $v['goods_num']);
            }
            $dis = $this->cardType($this->userId);
            $res['moneySum'] = $money*$dis;//折扣价

            //根据餐厅id获取餐厅的营业时间并计算配送时间段
            $ret = $this->mRestaurantInfo->getByPk($res['restaurant_id']);
            if ($ret) {
                $nowTime = time();
                //高峰时间转换为时间戳
                $high_time1 = strtotime(date('Y-m-d') . ' ' . $ret['high_time1'] . ':00');
                $high_time2 = strtotime(date('Y-m-d') . ' ' . $ret['high_time2'] . ':00');
                $high_time3 = strtotime(date('Y-m-d') . ' ' . $ret['high_time3'] . ':00');
                $high_time4 = strtotime(date('Y-m-d') . ' ' . $ret['high_time4'] . ':00');

                $time1 = strtotime(date('Y-m-d') . ' ' . $ret['time1'] . ':00');
                if ($high_time1 <= $nowTime && $nowTime <= $high_time2) {
                    $time2 = strtotime(date('Y-m-d') . ' ' . $ret['time2'] . ':00') + $ret['need_time'] * 60 + 2700;
                } else {
                    $time2 = strtotime(date('Y-m-d') . ' ' . $ret['time2'] . ':00') + $ret['need_time'] * 60;
                }


                $time3 = strtotime(date('Y-m-d') . ' ' . $ret['time3'] . ':00');
                if ($high_time3 <= $nowTime && $nowTime <= $high_time4) {
                    $time4 = strtotime(date('Y-m-d') . ' ' . $ret['time4'] . ':00') + $ret['need_time'] * 60 + 2700;
                } else {
                    $time4 = strtotime(date('Y-m-d') . ' ' . $ret['time4'] . ':00') + $ret['need_time'] * 60;
                }

                $time_o = array();
                for ($i = $time1; $i < $time2; $i = $i + 900) {
                    if ($high_time1 <= $nowTime && $nowTime <= $high_time2) {
                        if ($i >= ($nowTime + $ret['need_time'] * 60 + 1800)) {     //高峰时段多半个小时的配送时间
                            $time_o[] = date('H:i', $i) . '~' . date('H:i', $i + 900);
                        }
                    } else {
                        if ($i >= ($nowTime + $ret['need_time'] * 60)) {
                            $time_o[] = date('H:i', $i) . '~' . date('H:i', $i + 900);
                        }
                    }

                }

                $time_t = array();
                for ($i = $time3; $i < $time4; $i = $i + 900) {
                    if ($high_time3 <= $nowTime && $nowTime <= $high_time4) {
                        if ($i >= ($nowTime + $ret['need_time'] * 60 + 1800)) {
                            $time_t[] = date('H:i', $i) . '~' . date('H:i', $i + 900);
                        }
                    } else {
                        if ($i >= ($nowTime + $ret['need_time'] * 60)) {
                            $time_t[] = date('H:i', $i) . '~' . date('H:i', $i + 900);
                        }
                    }

                }

                if ($this->accountId == 25) {
                    $time = array('10:30~11:00', '11:30~12:00', '12:30~13:00', '16:00~16:30', '17:00~17:30', '18:00~18:30');
                } else {
                    $time = array_merge($time_o, $time_t);
                }
                $this->assign('restaurantId', $ret['restaurant_id']);
                $this->assign('time', $time);
                $this->assign('shipment', $ret['shipment']);
                $this->assign('restaurant_id', $ret['restaurant_id']);
            }
        }

        if (session("tableno_id")) {
            $tableName = M("RestaurantstyyTableno")->where(array("tableno_id" => session("tableno_id")))->getField("table_name");
            $this->assign("table_name", $tableName);
        }
        //$this->assign('address',$addressInfo);
        $this->assign('stime', $stime);
        $this->assign('order_id', $orderId);
        //$this->assign('notsend',$notsend);
        $this->assign('data', $res);
        $this->display($this->module_name . ':confirmorders');
    }

    /**
     *付款
     */
    public function orderPay()
    {
        $orderId = $this->_post('order_id');
        $restaurantId = $this->_post('restaurant_id');

        $memo = $this->_post('memo');
        $pay_type = $this->_post('pay_type');

        if (!$orderId) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '参数错误'));
        }

        //查询订单状态
        $orderInfo = $this->mOrder->getByPk($orderId);

        if ($orderInfo['status'] != 0) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '已经支付过了'));
        }

        //根据订单id获取订单商品表信息
        $orderGoodsInfo = $this->mOrderGoods->relation('restaurant_goods')->getList(array('order_id' => $orderId), array('goods_num', 'goods_price', 'goods_id'));

        $money = 0;
        $goodsName = array();
        $goodsNameCampusCard = array();
        if ($orderGoodsInfo) {
            foreach ($orderGoodsInfo as $v) {
                $goodsNameCampusCard[] = $v['restaurant_goods']['goods_name'];
                $money = $money + ($v['goods_num'] * $v['goods_price']);
                if ($v['restaurant_goods']['goods_sum'] <= 0) {
                    $goodsName[] = $v['restaurant_goods']['goods_name'];
                }
            }
        }

        if ($goodsName) {
            $str = implode('，', $goodsName);
            $this->ajaxReturn(array('status' => 'F', 'message' => $str . '等菜品库存不足，请重新选购'));
        }
        //查询餐厅的运费设置
        $restaurantInfo = $this->mRestaurantInfo->getByPk($restaurantId);
        // 判断餐厅是否营业中
        $nowTime = time();
        $time1 = strtotime(date('Y-m-d') . ' ' . $restaurantInfo['time1'] . ':00');
        $time2 = strtotime(date('Y-m-d') . ' ' . $restaurantInfo['time2'] . ':00');
        $time3 = strtotime(date('Y-m-d') . ' ' . $restaurantInfo['time3'] . ':00');
        $time4 = strtotime(date('Y-m-d') . ' ' . $restaurantInfo['time4'] . ':00');

        if (($time1 <= $nowTime && $nowTime <= $time2) || ($time3 <= $nowTime && $nowTime <= $time4)) {
            $shipment = $restaurantInfo['shipment'];
            $order_amout = $money + ($shipment > 0 ? $shipment : 0);
            $order_amout = $order_amout ? round($order_amout, 2) : 0.00;
            //更新订单信息
            $dis = $this->cardType($this->userId);
            $data = array(
                'send_time' => date('Y-m-d') . ' ',
                'memo' => $memo,
                'order_amount' => $order_amout*$dis,//折扣价,
                'goods_amount' => $order_amout,
                'freight' => $shipment > 0 ? $shipment : 0
            );
            $ret = M('RestaurantstyyOrder')->where(array('order_id' => $orderId))->save($data);
            if ($ret === false) {
                $this->ajaxReturn(array('status' => 'F', 'message' => '更新订单失败'));
            }

            $orderGoods = M('RestaurantstyyOrderGoods');
            $goods = $orderGoods->where(array('order_id'=>$orderId))->field('og_id,goods_price')->select();

            if($dis){
                    $money = $money*$dis;//商品打折价格
                    $data['order_amount'] = $money;
                    foreach($goods as $k=>$v){
                        $info = array();
                        $info = array(
                            'og_id'=>$v['og_id'],
                            'disconut_price'=>$v['goods_price']*$dis,
                            'disconut'=>$dis
                        );
                        $orderGoods->save($info);
                    }
                }else{
                foreach($goods as $k=>$v){
                    $info = array();
                    $info = array(
                        'og_id'=>$v['og_id'],
                        'disconut_price'=>$v['goods_price'],
                        'disconut'=>0
                    );
                    wLog(date("Y-m-d H:i:s")." _campusCardPay-4.2-info ".var_export($info,true),"styy");
                    $orderGoods->save($info);
                }
            }
            //获取订单信息
            $order = $this->mOrder->getByPk($orderId);

            if ($pay_type == 4) { //校园卡支付
                $cardno = M('User')->where(array('user_id' => $this->userId))->getField('cardno');

                if(!$cardno){
                    $this->ajaxReturn(array('status' => 'F', 'message' => '找不到卡号'));
                }

                if($order['order_amount']<=0){
                    throwException('支付失败', 2000);
                }

                $re = $this->_campusCardPay($cardno,$order['order_amount'],$order['order_sn']);

                if(!$re){
                    throwException('支付失败', 2000);
                }

                if($re['status'] != 'S'){
                    throwException($re['message'], 2000);
                }

                $this->campusNotify($orderId, $this->accountId,$cardno);

                $this->ajaxReturn(array('status' => 'CampusCard','message' => '支付成功'));
            } elseif ($pay_type == 1) { //微信支付
                $prepayData = $this->newPay($this->accountId, $order['order_sn'], '在线订餐', '', '');
                if (is_array($prepayData) && $prepayData['status'] == 'F') {
                    $this->ajaxReturn(array('status' => 'F', 'message' => $prepayData['message']));
                }
                $result = $prepayData->windowPay();
                if ($result['status'] == 'S') {
                    $this->ajaxReturn(array('status' => 'WS', 'message' => '调起微信成功', 'url' => $result['data'], 'order_id' => $orderId));
                } else {
                    $this->ajaxReturn(array('status' => 'F', 'message' => $result['message']));
                }
            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '该餐厅已停止营业'));
        }
    }


    public function cardType($user){
        $account = M('User')->where(array('user_id'=>$user,'cut_off'=>0))->getField('cardno');
        $campuscard = M("Campuscard")->where(array("account_id" => $this->accountId, "status" => 1))->find();
        $type = 'acc';   //号码类型
        vendor("CampusCard.CampusApiNew");
        $ser = new CampusApiNew($campuscard);
        $accountInfo = $ser->getAccountInfo($type,$account);

        //查找卡的类型
        $discount = M('RestaurantstyyCourier');
        $dis = $discount->where(array('card_num'=>$accountInfo['data'][0]['cardtype'],'cut_off'=>0,'status'=>1))->getField('discount');
        //判断是否打折
        if($dis){
            return $dis;
        }
        return 1;
    }

    /**
     * 校园卡支付
     * @param $account
     * @param $money
     * @Auth    : piyechao
     * @Now     :2017/12/15 19:13
     */
    private function _campusCardPay()
    {
        $order_ids= M('gc_restaurantstyy_order')->where('order_sn='.$order_no)->getField('order_id');
        $remark= $order_ids;
        var_dump( $remark);
        die();
        //$account=1,$money,$order_no
        $campuscard = M("Campuscard")->where(array("account_id" => $this->accountId, "status" => 1))->find();

        $mercacc = $campuscard['toaccount'];//'2001308';//商户号
        $type = 'acc';   //号码类型
//        $type = 'cardid';   //号码类型
        $mes = '001';       //账号类型
        vendor("CampusCard.CampusApiNew");
        $ser = new CampusApiNew($campuscard);
        $accountInfo = $ser->getAccountInfo($type,$account);

        if($accountInfo['status'] !== 'S'){

            return array("status"=>"F","message"=>$accountInfo['message']);
        }
        if(!isset($accountInfo['data'][0]['account'])){

            return array("status"=>"F","message"=>'查询失败');
        }
       $order_ids= M('gc_restaurantstyy_order')->where('order_sn='.$order_no)->getField('order_id');
        $remark= $order_ids;
       $res = $ser->tradePay($accountInfo['data'][0]['account'],$money,$mes,$mercacc,$remark,$order_no);

        if($res['status'] != 'S'){

            return array("status"=>"F","message"=>$res['data']['errmsg']);
        }
        //获得账号余额
        $accInfo = $ser->getAccInfo($accountInfo['data'][0]['account']);

        if($accInfo['status'] != 'S' || !isset($accInfo['data']['balance'])){

            return array("status"=>"F","message"=>'查询余额失败');
        }

        return array("status"=>"S","message"=>array('account'=>$accountInfo['data'][0]['account'],'balance'=>$accInfo['data']['balance']/100));
    }



    /**
     * 校园卡支付成功之后异步通知业务逻辑处理
     * @param $orderId
     * @param $account_id
     */
    public function campusNotify()
    {
//        $orderStatus = M('RestaurantstyyOrder')->where(array('order_id' => $orderId))->getField('status');
$orderId="62322";
        //tableno_id 1-50是2楼 50以上是1楼
        if(session('tableno_id')>50){
            $styyOrderNum = 'styyOrderNum3';
            $num1 = 'styyOrderNum4';
            $num = 8001;
        }else{
            $styyOrderNum = 'styyOrderNum11';
            $num1 = 'styyOrderNum2';
            $num = 9001;
        }
//获取ipadid
        $category_id=M('restaurantstyyOrderGoods')->where('order_id='.$orderId)->getField('category_id');
        $window_id= M('restaurantstyyGoodsCategory')->where('category_id='.$category_id)->getField('window_id');
        $iPadId = M('restaurantstyyWindowSn')->where('window_id='. $window_id)->getField('sn_num');
//        $iPadId=''
//        //生成餐桌号
//        $iPadId = session('iPadId');
       // $orderNum = RedisService::get($styyOrderNum);
        $orderNum = $this->orderNum($iPadId);

        var_dump($orderNum);

        //不存在 给个默认值0
        if (!$orderNum) {
            RedisService::set($styyOrderNum, $num);
        }
//        //走另一个的回调
//        require_once('ZduRestaurantApiAction.class.php');
//        $ZduRestaurant =new ZduRestaurantApiAction();
//        $ZduRestaurant->notify1($orderId);
//        $this->sendMessage($orderId,$this->userId);
//        die();
        //获取存的日期
        $time1 = RedisService::get($num1);
        //不存在 给个默认值当前日期
        if (!$time1) {
            $time1 = RedisService::set($num1, date('Y-m-d',time()));
        }
        //获取当前日期
        $time = date('Y-m-d',time());
        //存的日期和当前日期不一致 餐号归0 存的日期改成当天日期
        if($time != $time1){
            RedisService::set($styyOrderNum,$num);
            RedisService::set($num1,$time);
        }
        //餐号加1
        $orderNum = RedisService::incr($styyOrderNum);

//        $orderNum  = $orderNum+9000;
        $save_data = array(
            'status' => 1,
            'pay_type' => 4,
            'pay_time' => time(),
            'is_pay_notify' => 1,
            'order_num' => $orderNum,
            'card_number' => $number
        );
        M('RestaurantstyyOrder')->where(array('order_id' => $orderId))->save($save_data);
        //校园卡消息推送

        $this->sendMessage($orderId,$this->userId);
        M('RestaurantstyyOrderGoods')->where(array('order_id' => $orderId))->save(array('order_num' => $orderNum, 'pay_status' => 1));

        // 减库存,加销量
        $this->notify($orderId, $account_id,$orderNum);
    }


    /**
     * 获取餐号
     */
    public function orderNum($iPadId=''){
        $array = array('T11017CS00277','T11017CS00305','T11717BJ00146'); //1楼 sn设备号

        $array1 = array('T11017CS00308','T11017CS00298'); //2楼

        $kafei = 'T11017CS00317'; //1楼咖啡吧
        $zzw = 'T110175U00149'; //2楼蒸之味
        $lef = 'T110175U00042'; //2楼卤儿饭

        if(in_array($iPadId,$array)){ //1楼点餐
            $key = '';
            $styyOrderNum = 'styyOrderNum5';
            $num = 'styyOrderNum6';
            $num1 = 0;
        }elseif(in_array($iPadId,$array1)){ //2楼点餐机
            $key = 'M';
            $styyOrderNum = 'styyOrderNum7';
            $num = 'styyOrderNum8';
            $num1 = 20000;
        }elseif($iPadId==$kafei){ //1楼咖啡点餐机
            $key = 'K';
            $styyOrderNum = 'styyOrderNum13';
            $num = 'styyOrderNum14';
            $num1 = 30000;
        }elseif($iPadId==$zzw){ //2楼蒸之味
            $key = 'Z';
            $styyOrderNum = 'styyOrderNum15';
            $num = 'styyOrderNum16';
            $num1 = 10000;
        }elseif($iPadId==$lef){//2楼卤儿饭
            $key = 'L';
            $styyOrderNum = 'styyOrderNum17';
            $num = 'styyOrderNum18';
            $num1 = 0;
        }
        //获取餐号
        $orderNum = RedisService::get($styyOrderNum);
        //不存在 给个默认值0
        if (!$orderNum) {
            RedisService::set($styyOrderNum, $num1);
        }
        //获取存的日期
        $time1 = RedisService::get($num);
        //不存在 给个默认值当前日期
        if (!$time1) {
            $time1 = RedisService::set($num, date('Y-m-d',time()));
        }
        //获取当前日期
        $time = date('Y-m-d',time());
        //存的日期和当前日期不一致 餐号归0 存的日期改成当天日期
        if($time != $time1){
            RedisService::set($styyOrderNum,$num1);
            RedisService::set($num,$time);
        }
        //餐号加1
        $orderNum = RedisService::incr($styyOrderNum);
        $orderNum = str_pad($orderNum,5,0,STR_PAD_LEFT );
        return $orderNum = $key.$orderNum;
    }


    /**
     * 微支付异步通知
     */
    public function notify($orderId = '', $accountId = '', $orderNum='')
    {
        if ($orderId) {
            $mOrder = D('Base/RestaurantstyyOrder');
            $orderInfo = $mOrder->getByPk($orderId);
            if (($orderInfo['status'] == 1 || $orderInfo['status'] == 2) && $orderInfo['is_pay_notify'] == 1) {

                // 减库存,加销量
                $this->changeGoodsNum($orderId);

             //查询订单信息
                $info = $this->mOrder->relation(true)->getByPk($orderId);

                $orderGoodsArray = $this->mOrderGoods->field('goods_id,goods_num,goods_price,goods_name,print_type')->where(array('order_id'=>$orderId))->select();
                $printInfo = array('order_sn'=>$info['order_sn'],'order_num'=>$info['order_num'],'tableno_id'=>session('tableno_id'),'order_amount'=>$info['order_amount'],'pay_type'=>$info['pay_type'],'restaurant'=>$info['RestaurantInfo']['restaurant_name'],
                    'push_time'=>time(),'goods'=>$orderGoodsArray);

                //每次将订单丢入到队列中，先进先出
                $redis = RedisQueueService::getInstance();
                $redis->push('styy_print',$printInfo);
                $this->sendMessage($orderId,$this->userId);
            }
        }

    }

    /**
     *加销量，减库存
     * @param string $order_id
     */
    public function changeGoodsNum($order_id)
    {
        $info = D('Base/RestaurantstyyOrderGoods')->getList(array('order_id' => $order_id));
        if ($info) {
            foreach ($info as $v) {
                D('Base/RestaurantstyyGoods')->changeNum(array('goods_id' => $v['goods_id']), $v['goods_num']);
            }
        }
    }


    /***
     * @param string $orderId 订单id
     * @param string $userId  用户ID
     */
    public function sendMessage(){
         $userId="967";
         $orderId="179479";
        //微信用户open_id
        $openId = D('User')->where(array('user_id' => $userId))->getField('open_id');

        //订单信息
        $orderInfo = $this->mOrder->where(array('order_id'=>$orderId))->find();
        //餐厅信息
        $info = $this->mRestaurantInfo->getByPk($orderInfo['restaurant_id']);

        //微信模板id
        $templateId = 'ekcQpaU1PITvupiX08I65E8HoaGyVv-E2caQU-WuwfM';
        //标题
        $first = '您于'. date("Y年m月d日 H:i", time()).'的订单,菜肴已下厨,请耐心等待!';
        //餐厅名字
        if(session('tableno_id')){
            if(session('tableno_id')<50){
                $keyword1 = '麦思威';
            }else{
                $keyword1 = '二食堂';
            }
        }
        //餐厅电话
        $keyword2 = $info['mobile'];
        //点餐桌号s
        $keyword3 = session('tableno_id');
        //订单编号
        $keyword4 = $orderInfo['order_sn'];
        //备注说明
        $remark = '';
        //时间戳
        $time = $orderInfo['create_time'];
        $url = C('weixin') . "/restaurantstyy/ZduMobile/orderDetail/res_id/1/order_id/" . $orderId;
        //生成签名
        $array = array(
            'c' => 'smart',
            'a' => 'publicSendMsg',
            'url' => $url,
            'first' => $first,
            'keyword1' => $keyword1,
            'keyword2' => $keyword2,
            'keyword3' => $keyword3,
            'keyword4' => $keyword4,
            'remark'   => $remark,
            'time'     => $time,
            'touser'   => $openId,
            'template_id'   => $templateId,
        );

        $sign = $this->getSign($array);

        $array['sig'] = $sign;
        $array = http_build_query($array);
        $url = 'http://www.zulg.com/api.php?'.$array;

        $code = $this->curl($url);

    }

    /**
     * http请求
     * @param $url 请求地址
     * @param null $postFields 请求参数
     * @return mixed
     * @throws Exception
     */
    public function curl($url = '', $postParams= null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT,30);
        curl_setopt($ch, CURLOPT_HEADER,0);
        // post提交数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
        if(!is_array($postParams)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($postParams)
            ));
        }
        $output = json_decode(curl_exec($ch),true);
        curl_close($ch);
        //打印获得的数据
        return $output;
    }


    /**
     * @param $params  数组参数
     * @return string  获取签名
     */
    public function getSign($params,$type=''){

        $str = '';

        foreach($params as $k=>$v){
            $str .= $k . '=' .$v;
        }

        $str .='smart123456';

        $sign=md5($str);
        return $sign;
    }


    /**
     *评价订单
     */
    public function comment()
    {
        $score = $this->_post('score');
        $scoreSend = $this->_post('score_send');
        $scoreZl = $this->_post('score_zl');
        $restaurantId = $this->_post('id');
        $orderId = $this->_post('order_id');
        $comment = $this->_post('comment');
        //查询订单状态
        $info = $this->mOrder->getByPk($orderId);
        if ($info['status'] == 3) {
            //评分
            $ret = $this->mRestaurantInfo->comment(array('restaurant_id' => $restaurantId), $score, $scoreSend, $scoreZl);
            //将订单状态改为已评价
            $res = $this->mOrder->update(array('order_id' => $orderId, 'status' => 4, 'finish_time' => time(), 'comment' => $comment));
            if ($ret && $res) {
                $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功'));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败'));
            }
        } elseif ($info['status'] == 4) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '您已评价过了'));
        } elseif ($info['status'] < 3 || $info['status'] > 4) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '评价失败'));
        }
    }

    /**
     *取消订单
     */
    public function resetOrder()
    {
        $orderId = $this->_post('order_id');
        //查询订单状态
        $info = $this->mOrder->getByPk($orderId);
        if ($info['status'] == 0) {
            //将订单状态改为已取消
            $res = $this->mOrder->update(array('order_id' => $orderId, 'status' => 7, 'reset_time' => time(), 'reset_reason' => '用户自助取消'));
            if ($res) {
                $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功'));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败'));
            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '该订单不能取消'));
        }
    }

    /**
     *确认收货
     */
    public function sureOrder()
    {
        $orderId = $this->_post('order_id');
        //查询订单状态
        $info = $this->mOrder->getByPk($orderId);
        if ($info['status'] == 2) {
            //将订单状态改为已收货
            $res = $this->mOrder->update(array('order_id' => $orderId, 'status' => 3, 'receive_time' => time()));
            if ($res) {
                $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功'));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败'));
            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '该订单不能确认收货'));
        }
    }

    /**
     *订单详情
     */
    public function orderDetail()
    {
        $orderId = $this->_get('order_id');
        if (!$orderId) {
            echo '<script>alert("参数错误");history.back();</script>';
            exit();
        } else {
            //查询订单信息
            $info = $this->mOrder->relation(true)->getByPk($orderId);

            if ($info) {
                //查询管理员信息
                $manager = $this->mManager->getInfo(array('res_id' => $this->resId, 'restaurant_id' => $info['restaurant_id'], 'cut_off' => 0), array('username', 'mobile', 'wechat_user_id'));
                $tableName = M("RestaurantstyyTableno")->where(array("tableno_id" => $info['tableno_id']))->getField("table_name");
                if ($tableName) {
                    $info['table_name'] = $tableName;
                }
                if ($manager) {
                    $this->assign('manager_name', $manager['username']);
                    $this->assign('manager_mobile', $manager['mobile']);
                    // $info['manager_name'] = $manager['username'];
                    // $info['manager_mobile'] = $manager['mobile'];
                }
                foreach ($info['RestaurantOrderGoods'] as $key => $v) {
                    $info['money_sum'] = ($info['money_sum'] ? $info['money_sum'] : 0) + $v['goods_num'] * $v['goods_price'];
                }
                $count = count($info['RestaurantOrderGoods']);
            } else {
                $info = array();
                $count = 0;
            }
        }
        $this->assign('count', $count);
        $this->assign('data', $info);
        $this->display($this->module_name . ':orderdetail');
    }

    /**
     *获取单个分类下的所有商品信息
     */
    public function getGoodsInfo()
    {
        $categoryId = $this->_get('category_id');
        $restaurantId = $this->_get('restaurant_id');

        if (!$categoryId || !$restaurantId) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '参数错误'));
        } else {
            $data = array();
            //根据种类id和餐厅id查询所有商品信息
            $condition = array('restaurant_id' => $restaurantId, 'category_id' => $categoryId, 'cut_off' => 0, 'show' => 1, 'goods_sum' => array('gt', 0));
            $need = array('category_id', 'goods_id', 'goods_name', 'goods_desc', 'goods_sum', 'price', 'discount', 'goods_logo', 'saled_num');
            //获取当天供应的商品id
            $week = date('w');
            $weekGoods = $this->mWeekRelation->getList(array('res_id' => $this->resId, 'week' => $week), array('goods_id'));
            $weekGoodsId = array(0);
            if ($weekGoods) {
                foreach ($weekGoods as $v) {
                    $weekGoodsId[] = $v['goods_id'];
                }
            }

            $condition['goods_id'] = array('in', $weekGoodsId);
            $list = $this->mGoods->getList($condition, $need);

            //查询购物车信息
            $cartInfo = $this->mCart->relation(true)->getList(array('user_id' => $this->userId, 'restaurant_id' => $restaurantId));
            $cart_sum = 0;
            $cart_cost = 0;
            if ($cartInfo) {
                $cart_sum = count($cartInfo);
                foreach ($cartInfo as $v) {
                    if ($v['restaurant_goods']['discount'] == '0.00') {
                        $cart_cost = $cart_cost + ($v['goods_num'] * $v['restaurant_goods']['price']);
                    } else {
                        $cart_cost = $cart_cost + ($v['goods_num'] * $v['restaurant_goods']['discount']);
                    }
                }
            }

            $goodsId = array(0);
            foreach ($list as $v1) {
                $goodsId[] = $v1['goods_id'];

            }

            $cartNumInfo = $this->mCart->getList(array('goods_id' => array('in', $goodsId), 'user_id' => $this->userId, 'restaurant_id' => $restaurantId), array('goods_id', 'goods_num'));
            $cartNumInfo1 = array();

            foreach ($cartNumInfo as $ky => $vl) {
                $cartNumInfo1[$vl['goods_id']] = $vl['goods_num'];
            }

            foreach ($list as $key => $val) {
                $list[$key]['sale_num'] = $cartNumInfo1[$val['goods_id']] ? $cartNumInfo1[$val['goods_id']] : 0;
                if ($val['discount'] == '0.00') {
                    $list[$key]['discount'] = 0;
                }
            }
            //查询店铺信息
            $res = $this->mRestaurantInfo->getByPk($restaurantId);
            if ($res) {
                $minPrice = $res['min_price'];
            } else {
                $minPrice = 0.00;
            }
            if ($list) {
                $data['status'] = 'S';
                $data['message'] = '查询成功';
                $data['data']['goods_list'] = $list;
                $data['data']['cart_sum'] = $cart_sum;
                $data['data']['cart_cost'] = $cart_cost;
                $data['data']['restaurant_id'] = (int)$restaurantId;
                $data['data']['min_price'] = $minPrice;
            } else {
                $data['status'] = 'S';
                $data['message'] = '查询失败';
                $data['data']['restaurant_id'] = (int)$restaurantId;
                $data['data']['cart_cost'] = $cart_cost;

            }
            $this->ajaxReturn($data);
        }
    }

    /**
     *购物车添加、减少商品数量接口
     */
    public function updateCartNum()
    {
        $restaurantId = $this->_get('restaurant_id');
        $goodsId = $this->_get('goods_id');
        $goodsNum = $this->_get('sale_num') ? $this->_get('sale_num') : 0;

        if (!$restaurantId || !$goodsId) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '参数错误'));
        } else {
            //根据餐厅id查询餐厅信息
            $info = $this->mRestaurantInfo->getInfo(array('restaurant_id' => $restaurantId, 'cut_off' => 0));

            if (!$info) {
                $this->ajaxReturn(array('status' => 'F', 'message' => '餐厅不存在'));
            }

            if ($goodsNum == 0) {  //删除购物车物品
                $condition = array(
                    'restaurant_id' => $restaurantId,
                    'goods_id' => $goodsId,
                    'user_id' => $this->userId,
                );
                $res = $this->mCart->where($condition)->delete();
                if ($res === 0) {
                    $res = true;
                }
            } else {  //添加购物车
                $data = array(
                    'restaurant_id' => $restaurantId,
                    'goods_id' => $goodsId,
                    'goods_num' => $goodsNum,
                    'user_id' => $this->userId,
                );

                $ret = $this->mCart->getInfo(array('goods_id' => $goodsId, 'user_id' => $this->userId, 'restaurant_id' => $restaurantId));
                if ($ret) {

                    $res = $this->mCart->where(array('cart_id' => $ret['cart_id']))->save($data);
                } else {

                    $res = $this->mCart->add($data);
                }

            }

            //查询购物车信息
            $cartInfo = $this->mCart->relation(true)->getList(array('user_id' => $this->userId, 'restaurant_id' => $restaurantId));
            $cart_sum = 0;
            $cart_cost = 0;
            if ($cartInfo) {
                $cart_sum = count($cartInfo);
                foreach ($cartInfo as $v) {
                    if ($v['restaurant_goods']['discount'] == '0.00') {
                        $cart_cost = $cart_cost + ($v['goods_num'] * $v['restaurant_goods']['price']);
                    } else {
                        $cart_cost = $cart_cost + ($v['goods_num'] * $v['restaurant_goods']['discount']);
                    }
                }
            }

            //查询当前物品的单价
            $goodsInfo = $this->mGoods->getByPk($goodsId);
            if ($goodsInfo['discount'] == '0.00') {
                $good_price = number_format($goodsInfo['price'] * $goodsNum);
            } else {
                $good_price = number_format($goodsInfo['discount'] * $goodsNum);
            }

            if ($res !== false) {
                $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功', 'data' => array('cart_sum' => $cart_sum, 'cart_cost' => $cart_cost, 'min_price' => $info['min_price'], 'goods_price' => $good_price, 2, '.', ' ')));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败'));
            }
        }
    }

    /**
     *查询购物车信息
     */
    public function getCartInfo()
    {
        $restaurantId = $this->_get('restaurant_id');
        if ($restaurantId) {
            $cartInfo = $this->mCart->relation(true)->getList(array('user_id' => $this->userId, 'restaurant_id' => $restaurantId));
            $list = array();
            if ($cartInfo) {
                foreach ($cartInfo as $key => $v) {
                    $list[$key]['cart_id'] = $v['cart_id'];
                    $list[$key]['goods_id'] = $v['goods_id'];
                    $list[$key]['sale_num'] = $v['goods_num'];
                    if ($v['restaurant_goods']['discount'] == '0.00') {
                        $list[$key]['price'] = $v['restaurant_goods']['price'] * $v['goods_num'];
                    } else {
                        $list[$key]['price'] = $v['restaurant_goods']['discount'] * $v['goods_num'];
                    }
                    $list[$key]['goods_name'] = $v['restaurant_goods']['goods_name'];
                }
            }
            $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功', 'data' => $list));
        } else {
            $this->ajaxReturn(array('status' => 'S', 'message' => '参数错误'));
        }
    }

    /**
     *购物车结算接口
     */
    public function getOrderUrl()
    {
        $restaurantId = $this->_get('restaurant_id');
        //查询餐厅起送价
        $info = $this->mRestaurantInfo->getByPk($restaurantId);
        // 判断餐厅是否营业中
        $nowTime = time();
        $time1 = strtotime(date('Y-m-d') . ' ' . $info['time1'] . ':00');
        $time2 = strtotime(date('Y-m-d') . ' ' . $info['time2'] . ':00');
        $time3 = strtotime(date('Y-m-d') . ' ' . $info['time3'] . ':00');
        $time4 = strtotime(date('Y-m-d') . ' ' . $info['time4'] . ':00');
        $time5 = strtotime(date('Y-m-d') . ' ' . $info['time5'] . ':00');
        $time6 = strtotime(date('Y-m-d') . ' ' . $info['time6'] . ':00');
        if (($time1 <= $nowTime && $nowTime <= $time2) || ($time3 <= $nowTime && $nowTime <= $time4) || ($time5 <= $nowTime && $nowTime <= $time6)) {
            //查询当前用户购物车中当前餐厅的所有商品
            if ($restaurantId) {
                $cartInfo = $this->mCart->relation(true)->getList(array('user_id' => $this->userId, 'restaurant_id' => $restaurantId));
                $goodsList = array();
                $moneySum = 0;
                foreach ($cartInfo as $key => $v) {
                    if ($v['goods_num'] > $v['restaurant_goods']['goods_sum']) {
                        $goodsList[] = $v['restaurant_goods']['goods_name'];
                    }
                    if ($v['restaurant_goods']['discount'] == '0.00') {
                        $moneySum = $moneySum + $v['goods_num'] * $v['restaurant_goods']['price'];
                    } else {
                        $moneySum = $moneySum + $v['goods_num'] * $v['restaurant_goods']['discount'];
                    }
                }
                if ($moneySum < $info['min_price']) {
                    $this->ajaxReturn(array('status' => 'F', 'message' => '未达到起送价'));
                }

                if (!empty($goodsList)) {
                    $str = implode('，', $goodsList);
                    $this->ajaxReturn(array('status' => 'F', 'message' => $str . '等菜品库存不足，请重新选购'));
                }

                if ($cartInfo) {
                    $windowSn = M('RestaurantstyyWindowSn');
                    $categoryId = $this->mGoods->where(array('goods_id'=>$cartInfo[0]['goods_id']))->getField('category_id');
                    $windowId = $this->mGoodsCategory->where(array('category_id'=>$categoryId))->getField('window_id');
                    $sn = $windowSn->where(array('window_id'=>$windowId,'cut_off'=>0))->getField('sn_num');
                    //获取订单号
                    $orderSn = $this->getOrderSn('styy');
                    //生成订单
                    $data = array();
                    $data['order_sn'] = $orderSn['data'];  //生成订单号
                    $data['status'] = 0;
                    $data['user_id'] = $this->userId;
                    $data['res_id'] = $this->resId;
                    $data['restaurant_id'] = $restaurantId;
                    $data['create_time'] = time();
                    $data['is_pay_notify'] = 0;
                    $data['tableno_id'] = session("tableno_id");
                    $data['sn'] = $sn;
                    //往订单表插入数据
                    $ret = $this->mOrder->add($data);
                    if ($ret) {
                        //将购物车中的商品写入订单物品表
                        foreach ($cartInfo as $v) {
                            if ($v['restaurant_goods']['discount'] == '0.00') {
                                $good_price = $v['restaurant_goods']['price'];
                            } else {
                                $good_price = $v['restaurant_goods']['discount'];
                            }
                            //查询对应的打印类型
                            $type = M('RestaurantstyyGoods')->where(array('goods_id' => $v['goods_id']))->getField('print_type');
                            $orderGoodsInfo[] = array(
                                'order_id' => $ret,
                                'goods_id' => $v['goods_id'],
                                'restaurant_id' => $restaurantId,
                                'order_sn' => $data['order_sn'],
                                'goods_num' => $v['goods_num'],
                                'create_time' => time(),
                                'user_id' => $this->userId,
                                'goods_name' => $v['restaurant_goods']['goods_name'],
                                'goods_price' => $good_price,
                                'goods_logo' => $v['restaurant_goods']['goods_logo'],
                                'category_id' => $v['restaurant_goods']['category_id'],
                                'window_id' => M('RestaurantstyyGoodsCategory')->where(array('category_id' => $v['restaurant_goods']['category_id']))->getField('window_id'),
                                'tableno_id' => session("tableno_id"),
                                'print_type' => $type
                            );
                        }
                        $res = M("RestaurantstyyOrderGoods")->addAll($orderGoodsInfo);
                        if ($res !== false) {
                            //删除购物车表该用户当然餐厅的数据
                            $this->mCart->where(array('user_id' => $this->userId, 'restaurant_id' => $restaurantId))->delete();
                            $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功', 'url' => '/index.php?g=restaurantstyy&m=ZduMobile&a=confirmorders&res_id=' . $this->resId . '&order_id=' . $ret));
                        } else {
                            $this->ajaxReturn(array('status' => 'F', 'message' => '插入订单物品失败'));
                        }
                    } else {
                        $this->ajaxReturn(array('status' => 'F', 'message' => '生成订单失败'));
                    }
                } else {
                    $this->ajaxReturn(array('status' => 'F', 'message' => '请选择商品'));
                }
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '参数错误'));
            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '该餐厅已停止营业'));
        }
    }

    /**
     *发货列表页面
     */
    public function sendList()
    {
        //查询是否是管理员
        $manager = $this->mManager->getList(array('res_id' => $this->resId, 'wechat_user_id' => session('wechatUserId'), 'cut_off' => 0));
        if (empty($manager)) {
            $this->error('对不起，你不是餐厅管理员，无法操作！');
        }

        $num = 10;
        $condition = array('res_id' => $this->resId, 'status' => array('in', array(1, 2, 3, 4)));
        $count = $this->mOrder->getCount($condition);
        $page = new Page($count, $num);
        $limit = $page->firstRow . ',' . $page->listRows;;
        //查询状态为已付款，已发货，已确认收货，已评价的订单
        $list = $this->mOrder->relation('RestaurantstyyOrderGoods')->getList($condition, '', 'status asc,pay_time desc', '', $limit);
        $this->assign('pageCount', ceil($count / $num));
        $this->assign('data', $list);
        $this->display($this->module_name . ':sendlist');
    }

    /**
     *滑动加载发货列表
     */
    public function ajaxGetList()
    {
        //查询该微信下的所有餐厅
        $num = 10;
        $condition = array('res_id' => $this->resId, 'status' => array('in', array(1, 2, 3, 4)));
        $count = $this->mOrder->getCount($condition);
        $page = new Page($count, $num);
        $limit = $page->firstRow . ',' . $page->listRows;;
        //查询状态为已付款，已发货，已确认收货，已评价的订单
        $list = $this->mOrder->relation('RestaurantstyyOrderGoods')->getList($condition, '', 'status asc,pay_time desc', '', $limit);
        $data = array();
        if ($list) {
            foreach ($list as $key => $val) {
                $data[$key]['order_id'] = $val['order_id'];
                $data[$key]['order_sn'] = $val['order_sn'];
                $data[$key]['pay_time'] = date('Y-m-d H:i', $val['pay_time']);
                $data[$key]['user_name'] = $val['user_name'];
                $data[$key]['status'] = $val['status'];
                $data[$key]['mobile'] = $val['mobile'];
                $data[$key]['address'] = $val['address'];
                if ($val['RestaurantOrderGoods']) {
                    $str = '';
                    foreach ($val['RestaurantOrderGoods'] as $v) {
                        $str = $str . '<p>' . $v['goods_name'] . '<span class="pull-right">x' . $v['goods_num'] . '</span></p>';
                    }
                    $data[$key]['goods_info'] = $str;
                } else {
                    $data[$key]['goods_info'] = '';
                }

            }
        }
        $this->ajaxReturn(array('status' => 'S', 'data' => $data));
    }

    /**
     *发货操作
     */
    public function send()
    {
        $id = $this->_post('id');
        //查询是否是管理员
        $manager = $this->mManager->getInfo(array('res_id' => $this->resId, 'wechat_user_id' => session('wechatUserId'), 'cut_off' => 0));
        if (empty($manager)) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '对不起，你不是餐厅管理员，无法操作！'));
        }

        //修改订单状态
        $res = $this->mOrder->update(array('order_id' => $id, 'status' => 2, 'ship_time' => time(), 'send_user' => $manager['username']));
        if ($res) {
            //查询订单信息
            $orderInfo = $this->mOrder->getByPk($id);
            import("@.Msgtpl.Base.RestaurantstyyMsgtpl");
            $accountInfo = D('Restaurantstyy')->getInfo(array('res_id' => $this->resId), array('account_id'));
            $wechatInfo = D('Wechat')->getInfo(array('account_id' => $accountInfo['account_id']), array('wechat_id'));
            $RestaurantMsgtpl = new RestaurantstyyMsgtpl($wechatInfo['wechat_id']);
            $RestaurantMsgtpl->sendInfoToUser($orderInfo, $accountInfo['account_id']);
            $this->ajaxReturn(array('status' => 'S', 'message' => '发货成功'));
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '发货失败'));
        }
    }

    /**
     *打印信息
     * @param $orderId
     */
    public function useWifiPrintInfo($orderId)
    {
        //$orderId=8;
        $mOrder = D('Base/RestaurantstyyOrder');
        $mGoods = D('Base/RestaurantstyyGoods');
        $mWindow = D('Base/RestaurantstyyWindow');
        //$orderId = $this->_get('order_id');
        //查询订单信息
        $info = $mOrder->relation(true)->getByPk($orderId);
        //$info = $this->mOrder->relation(true)->getByPk($orderId);
        if ($info) {
            $goodsCold = array();
            $windowInfo = array();

            foreach ($info['RestaurantOrderGoods'] as $key => $v) {
                //查询菜品对应的种类对应档口及打印机信息
                $list = $mGoods->relation('RestaurantstyyGoodsCategory')->getByPk($v['goods_id']);
                //$list = $this->mGoods->relation('RestaurantGoodsCategory')->getByPk($v['goods_id']);
                $wInfo = $mWindow->getByPk($list['window_id']);
                //$wInfo = $this->mWindow->getInfo($list['window_id']);
                $windowInfo[$wInfo['window_id']]['window_id'] = $wInfo['window_id'];
                $windowInfo[$wInfo['window_id']]['print_key'] = $wInfo['print_key'];
                $windowInfo[$wInfo['window_id']]['print_dno'] = $wInfo['print_dno'];
                $windowInfo[$wInfo['window_id']]['print_username'] = $wInfo['print_username'];
                $windowInfo[$wInfo['window_id']]['print_count'] = $wInfo['print_count'];
                $goodsCold[$v['window_id']][] = str_pad($v['goods_name'], 18, '　') . str_pad($v['goods_num'], 4) . '￥' . number_format($v['goods_num'] * $v['goods_price'], 2) . '\n';
                $windowInfo[$wInfo['window_id']]['order_amount'] += $v['goods_num'] * $v['goods_price'];
                //$goodsHot = $goodsHot . $v['goods_name'] . '    ' . $v['goods_num'] . '     ' . $v['goods_num']*$v['goods_price'] . '\n';
            }

            foreach ($goodsCold as $one => $on) {
                $windowInfo[$one]['goods'] = implode('', $on);
            }

            $headerStr = '';
            if ($this->accountId == 2) {
                $headerStr = '|2http://weixin.qq.com/r/7UzVzQPEGF5nrUeu9xn-' . '\r\n';
            }
            if ($windowInfo) {
                if ($info['pay_type'] == 1) {
                    $payType = '微信';
                }
                if ($info['pay_type'] == 2) {
                    $payType = '支付宝';
                }
                if ($info['pay_type'] == 4) {
                    $payType = '一卡通';
                }
                if ($info['pay_type'] == 5) {
                    $payType = '校园卡';
                }
                foreach ($windowInfo as $val) {
                    $content = $headerStr .
                        '|5================================' . '\r\n' .
                        '|4餐厅名：' . $info['RestaurantInfo']['restaurant_name'] . '\r\n' .
                        '|4餐号：' . $info['order_num'] . '\r\n';
                    if ($info['tableno_id']) {
                        $content .= '|4桌号：' . $info['tableno_id'] . '\r\n';
                    }
                    $content .= '|5订单编号：' . $info['order_sn'] . '\r\n' .
                        '|5打印时间:' . date('Y-m-d H:i:s') . '\n' .
                        '|5支付方式:' . $payType . '\n' .
                        '|4------------------------' . '\n' .
                        str_pad('商品名称', 18, '　') . str_pad('数量', 8) . '小计' . '\n' . $val['goods'] .
                        '------------------------' . '\n' .
                        '总计：' . $val['order_amount'] . '元' . '\n';
                    $str = $val['print_key'] . $val['print_dno'] . 'aykj';
                    $keyInfo = md5($str);
                    $username = $val['print_username'];
                    $dno = $val['print_dno'];
                    $times = $val['print_count'];

                    $this->useWifiPrint($times, $keyInfo, $content, $username, $dno);
                }
            }
        }
    }

    /**
     *使用wifi打印机打印
     * @param int $times 打印次数
     * @param string $key 加密字符串
     * @param string $content 打印内容
     * @param string $username 官网用户名
     * @param string $dno 设备编号
     * @param int $mode 打印模式（0 混合打印;1文本打印; 2二维码打印;3条码打印）
     * @param string $msgno 订单编号（不传则自动生成）
     * @param string $op 操作类型（pf:打印操作  cx：查询打印机状态 cxdd：查询订单状态）
     * @param string $qr 支付宝二维码图片链接地址（可选）
     * @return array
     */
    function useWifiPrint($times = 3, $key, $content, $username, $dno, $mode = 0, $msgno = '', $op = 'pf', $qr = '')
    {
        /**
         * 返回状态码
         * 0 成功
         * 1 订单发送失败';
         * 200 查询失败';
         * 201 不存在当前设备';
         * 300 二维码打印成功';
         * 301 二维码打印失败';
         * 401 查询订单失败';
         * 900 没有相关操作';
         * 901 操作错误';
         * -2 验证错误';
         * -3 绑定设备不属于该用户';
         * -4 打印类型错误';
         * -5 该用户无效';
         * -7 设备号';
         * -8 参数错误';
         * -102 条形码打印存在汉字';
         * -103 组合打印类型不含有前缀';
         * .
         * '序号：' . ($i + 1) . '\r\n' */

        $result = array();
        for ($i = 0; $i < $times; $i++) {
            $url = 'http://121.43.235.40/WS/DealData.ashx';
            $fields = array(
                'op' => $op,
                'content' => $content .
                    '|5================================' . '\r\n' .
                    '|4   青橄榄网络技术支持',
                'key' => $key,
                'unm' => $username,
                'dno' => $dno,
                'mode' => '|' . $mode,
                'msgno' => $msgno,
                'qr' => $qr,
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, count($fields)); // 启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // 在HTTP中的“POST”操作。如果要传送一个文件，需要一个@开头的文件名

            ob_start();
            curl_exec($ch);

            $result[] = ob_get_contents();
            ob_end_clean();
        }
        return $result;
    }

    /**
     *打印信息
     * @param $orderId
     */
    public function useWifiPrintInfoTest($orderId)
    {

        $mOrder = D('Base/RestaurantstyyOrder');
        $mGoods = D('Base/RestaurantstyyGoods');
        $mWindow = D('Base/RestaurantstyyWindow');
        //$orderId = $this->_get('order_id');
        //查询订单信息
        $info = $mOrder->relation(true)->getByPk($orderId);
        //$info = $this->mOrder->relation(true)->getByPk($orderId);

        if ($info) {
            $goods = '';
            $windowInfo = array();
            foreach ($info['RestaurantOrderGoods'] as $key => $v) {
                //查询菜品对应的种类对应档口及打印机信息
                $list = $mGoods->relation('RestaurantstyyGoodsCategory')->getByPk($v['goods_id']);
                //$list = $this->mGoods->relation('RestaurantGoodsCategory')->getByPk($v['goods_id']);
                $wInfo = $mWindow->getByPk($list['window_id']);
                //$wInfo = $this->mWindow->getInfo($list['window_id']);
                $windowInfo[$wInfo['window_id']]['window_id'] = $wInfo['window_id'];
                $windowInfo[$wInfo['window_id']]['print_key'] = $wInfo['print_key'];
                $windowInfo[$wInfo['window_id']]['print_dno'] = $wInfo['print_dno'];
                $windowInfo[$wInfo['window_id']]['print_username'] = $wInfo['print_username'];
                $windowInfo[$wInfo['window_id']]['print_count'] = $wInfo['print_count'];

                $goods = $goods . $v['goods_name'] . '…' . $v['goods_amount'] . '*' . $v['goods_num'] . '）\r\n';
            }

            $headerStr = '';
            if ($this->accountId == 2) {
                $headerStr = '|2http://weixin.qq.com/r/7UzVzQPEGF5nrUeu9xn-' . '\r\n';
            }
            if ($windowInfo) {
                foreach ($windowInfo as $val) {
                    $content = $headerStr .
                        '|5================================' . '\r\n' .
                        '餐厅名：' . $info['RestaurantInfo']['restaurant_name'] . '\r\n' .
                        '订单号：' . $info['order_sn'] . '\r\n' .
                        '桌号：' . $info['order_num'] . '\r\n' .
                        '订单内容：\r\n' . $goods .
                        '总计：' . $info['order_amount'] . '\r\n' .
                        '就餐时间：' . $info['send_time'] . '\r\n' .
                        '备注：' . $info['memo'] . '\r\n';
                    $str = $val['print_key'] . $val['print_dno'] . 'aykj';
                    $keyInfo = md5($str);
                    $username = $val['print_username'];
                    $dno = $val['print_dno'];
                    $times = $val['print_count'];
                    $this->useWifiPrint($times, $keyInfo, $content, $username, $dno);
                }
            }
        }
    }

    /**
     *使用wifi打印机打印
     * @param int $times 打印次数
     * @param string $key 加密字符串
     * @param string $content 打印内容
     * @param string $username 官网用户名
     * @param string $dno 设备编号
     * @param int $mode 打印模式（0 混合打印;1文本打印; 2二维码打印;3条码打印）
     * @param string $msgno 订单编号（不传则自动生成）
     * @param string $op 操作类型（pf:打印操作  cx：查询打印机状态 cxdd：查询订单状态）
     * @param string $qr 支付宝二维码图片链接地址（可选）
     * @return array
     */
    function useWifiPrintTest($times = 3, $key, $content, $username, $dno, $mode = 0, $msgno = '', $op = 'pf', $qr = '')
    {
        /**
         * 返回状态码
         * 0 成功
         * 1 订单发送失败';
         * 200 查询失败';
         * 201 不存在当前设备';
         * 300 二维码打印成功';
         * 301 二维码打印失败';
         * 401 查询订单失败';
         * 900 没有相关操作';
         * 901 操作错误';
         * -2 验证错误';
         * -3 绑定设备不属于该用户';
         * -4 打印类型错误';
         * -5 该用户无效';
         * -7 设备号';
         * -8 参数错误';
         * -102 条形码打印存在汉字';
         * -103 组合打印类型不含有前缀';
         * */
        $result = array();
        for ($i = 0; $i < $times; $i++) {
            $url = 'http://121.43.235.40/WS/DealData.ashx';
            $fields = array(
                'op' => $op,
                'content' => $content .
                    '序号：' . ($i + 1) . '\r\n' .
                    '================================' . '\r\n' .
                    '|4技术支持：杭州青橄榄网络技术有限公司',
                'key' => $key,
                'unm' => $username,
                'dno' => $dno,
                'mode' => '|' . $mode,
                'msgno' => $msgno,
                'qr' => $qr,
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, count($fields)); // 启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // 在HTTP中的“POST”操作。如果要传送一个文件，需要一个@开头的文件名

            ob_start();
            curl_exec($ch);

            $result[] = ob_get_contents();
            ob_end_clean();
        }
        return $result;
    }

    /**
     * 错误提示
     */
    public function error($tips = '页面加载中', $times = 2, $url = "", $noRedirect = 0)
    {
        $times = $times * 1000;
        $this->assign('tips', $tips);
        $this->assign('times', $times);
        if ($url == '') {
            $url = "/base/center/center/account_id/" . $this->accountId;
        }
        $this->assign('url', $url);
        $this->assign("no_redirect", $noRedirect);
        $this->display($this->module_name . ':error');
        exit;
    }


    /**
     *定时任务处理
     */
    public function timeTask()
    {
        $list = $this->mRestaurant->getList(array('res_id' => $this->resId));
        if ($list) {
            foreach ($list as $v) {
                $this->receive($this->resId, $v['receive_time'], $v['comment_time']);
            }
        }
    }

    /**
     *发货5天自动确认收货
     */
    public function receive($resId, $receiveTime, $commentTime)
    {
        set_time_limit(0);
        //查询已发货超过设置天数的订单号
        $list = $this->mOrder->getList(array('res_id' => $resId, 'status' => 2, 'ship_time' => array('lt', time() - $receiveTime * 3600)), array('order_id'));

        $orderIdList = array();
        if ($list) {
            foreach ($list as $v) {
                $orderIdList[] = $v['order_id'];
            }
        }

        if ($orderIdList) {
            //批量自动确认收货
            $this->mOrder->where(array('order_id' => array('in', $orderIdList)))->save(array('status' => 3, 'receive_time' => time()));
        }

        $this->commentOrder($resId, $commentTime);
        $this->close($this->resId);
    }

    /**
     *确认收货15天自动好评(全部5星好评，文件评价为“好评”)
     */
    public function commentOrder($resId, $commentTime)
    {
        set_time_limit(0);
        //查询收货后需要在设置天数自动好评的订单
        $list = $this->mOrder->getList(array('res_id' => $resId, 'status' => 3, 'receive_time' => array('lt', time() - $commentTime * 3600)), array('order_id', 'restaurant_id'));

        $orderList = array();
        if ($list) {
            foreach ($list as $v) {
                $orderList[] = $v['order_id'];
                $this->mRestaurantInfo->comment(array('restaurant_id' => $v['restaurant_id']), 5, 5, 5);
            }
        }

        if ($orderList) {
            //批量评价
            $this->mOrder->where(array('order_id' => array('in', $orderList)))->save(array('status' => 4, 'finish_time' => time(), 'comment' => '好评'));
        }
    }

    /**
     *关闭未付款订单
     */
    public function close($resId)
    {
        //查询在设置时间数自动关闭的订单
        if (time() >= strtotime(date('Y-m-d 22:00:00')) && time() < strtotime(date('Y-m-d')) + 86400) {
            $list = $this->mOrder->getList(array('res_id' => $resId, 'status' => 0), array('order_id', 'restaurant_id'));

            $orderList = array();
            if ($list) {
                foreach ($list as $v) {
                    $orderList[] = $v['order_id'];
                }
            }
            if ($orderList) {
                //批量关闭
                $this->mOrder->where(array('order_id' => array('in', $orderList)))->save(array('status' => 8, 'close_time' => time(), 'close_reason' => '超时未付款'));
            }
        }
    }

    /**
     * 每日统计
     */
    public function dayStatic()
    {
        //没权限跳转地址
        $url = U('index', array('res_id' => $this->resId));
        //判断用户是否是管理员
        $wechatUserId = session('wechatUserId');
        if (!$wechatUserId) {
            $this->error('参数错误', 3, $url);
        }
        $where = array('wechat_user_id' => $wechatUserId, 'res_id' => $this->resId, 'cut_off' => 0);
        $restaurantId = M('RestaurantstyyManager')->where($where)->getField('restaurant_id');
        if (!$restaurantId) {
            $this->error('暂无权限', 3, $url);
        }
        if (IS_AJAX) {
            $dateSum = 4;//获得最近4天的数据
            $endTime = strtotime(date("Y-m-d"));
            $startTime = $endTime - 3600 * 24 * $dateSum;
            $yesterday = $endTime - 3600 * 24;//昨天
            $list = $yesterdayData = array();
            $k = 0;
            for ($i = $startTime; $i < $endTime; $i = $i + 3600 * 24) {
                $list['day'][$k] = date('m.j', $i);

                $condition = array('create_time' => array('between', array($i, $i + 3600 * 24)), 'restaurant_id' => $restaurantId, 'res_id' => $this->resId, 'status' => array('in', array(1, 2, 3, 4)));
                $list['money'][$k] = $this->mOrder->getSum($condition, 'order_amount');
                $list['money'][$k] = $list['money'][$k] ? $list['money'][$k] : 0;

                $list['num'][$k] = $this->mOrder->getCount($condition);
                $list['num'][$k] = $list['num'][$k] ? $list['num'][$k] : 0;

                $list['avg'][$k] = $list['num'][$k] ? round($list['money'][$k] / $list['num'][$k], 2) : 0;

                if ($i == $yesterday) {
                    $yesterdayData = array(
                        'time' => date('Y-m-d', $i),
                        'num' => $list['num'][$k],
                        'money' => $list['money'][$k],
                    );
                }
                $k++;
            }

            //昨日数据，统计订单数和订单金额
            $data = array(
                'yesterdayData' => $yesterdayData,
                'list' => $list
            );
            $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功', 'data' => $data));
        }

        $this->display($this->module_name . ':daystatic');
    }



    /**
     * 保存离线订单  跑定时
     */
    public function doLog()
    {
        $log = M('RestaurantstyyLog')->where(array('cut_off' => 0))->field('id,content')->select();

        //模拟下单操作,但是已经付款
        $mOrder = M('RestaurantstyyOrder');
        $mOrderGoods = M('RestaurantstyyOrderGoods');

        foreach ($log as $k => $v) {

            $info = json_decode($v['content'], true);
            $list = json_decode($info['orderList'], true);
            foreach ($list as $k1 => $v1) {

                $data = array();
                //生成订单号
                $orderSn = $this->getOrderSn('styyApi');
                //生成订单
                $data['order_sn'] = 'L' . $orderSn['data'];
                $data['order_num'] = 0;
                $data['user_id'] = 0;
                $data['res_id'] = $info['res_id'];
                $data['restaurant_id'] = $info['restaurant_id'];
                $data['create_time'] = strtotime($v1['time']);
                $data['pay_time'] = strtotime($v1['time']);
                $data['status'] = 2;//已支付
                $data['is_pay_notify'] = 1;
                $data['pay_notify_time'] = strtotime($v1['time']);
                $data['pay_type'] = 4;//校园卡支付
                $data['is_same'] = 1;//已同步
                $data['order_amount'] = $v1['order_money'];
                $data['goods_amount'] = $v1['order_money'];
                $data['cut_off'] = 0;
                $mOrder->startTrans();
                $res = $mOrder->add($data);
                foreach ($v1['goods'] as $key => $value) {
                    $arr = $this->mGoods->where(array('goods_id' => $value['goods_id']))->field('price,goods_name,goods_logo')->find();
                    $goods = array();
                    $goods['order_id'] = $res;
                    $goods['goods_id'] = $value['goods_id'];
                    $goods['restaurant_id'] = $info['restaurant_id'];
                    $goods['order_sn'] = $data['order_sn'];
                    $goods['goods_num'] = $value['goods_num'];
                    $goods['goods_price'] = $arr['price'];
                    $goods['create_time'] = strtotime($v1['time']);
                    $goods['goods_name'] = $arr['goods_name'];
                    $goods['goods_logo'] = $arr['goods_logo'];
                    $goods['order_num'] = 0;
                    $goods['pay_status'] = 1;
                    $goods['goods_status'] = 2;
                    $goods['is_same'] = 1;
                    $result = $mOrderGoods->add($goods);
                    if ($res && $result) {
                        $mOrder->commit();
                        M('RestaurantstyyLog')->where(array('cut_off' => 0))->setField('cut_off',1);
                    } else {
                        $mOrder->rollback();
                        break;
                    }
                }
            }
        }
    }

        public  function test(){
            $order_no=$_POST['order_sn'];
            $order_ids= M('RestaurantstyyOrder')->where('order_sn='.$order_no)->getField('order_id');
            $remark= $order_ids;
            var_dump( $remark);
            die();
        }


}